package com.qst.repository;

import com.qst.pojo.entity.Item;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
 * 物品数据访问层
 */
@Repository
public interface ItemRepository extends JpaRepository<Item, Integer> {
    
    /**
     * 根据物品名称查找
     */
    Optional<Item> findByName(String name);
    
    /**
     * 检查物品名称是否存在
     */
    boolean existsByName(String name);
    
    /**
     * 根据分类查询
     */
    Page<Item> findByCategory(String category, Pageable pageable);
    
    /**
     * 根据状态查询
     */
    Page<Item> findByStatus(Item.ItemStatus status, Pageable pageable);
    
    /**
     * 根据条件分页查询物品
     */
    @Query("SELECT i FROM Item i WHERE " +
           "(:keyword IS NULL OR i.name LIKE %:keyword% OR i.description LIKE %:keyword%) AND " +
           "(:category IS NULL OR i.category = :category) AND " +
           "(:status IS NULL OR i.status = :status)")
    Page<Item> findByConditions(@Param("keyword") String keyword,
                                 @Param("category") String category,
                                 @Param("status") Item.ItemStatus status,
                                 Pageable pageable);
}

